package com.hualian.coupon.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hualian.coupon.exception.BusinessException;
import com.hualian.coupon.pojo.Manager;
import com.hualian.coupon.service.ManagerService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Lxd
 * @Description TODO
 * @date 2020/10/22 18:33
 * @Version 1.0
 */

@RestController
@RequestMapping("/man")
public class ManagerController {

    @Resource
    ManagerService managerService;

    @PostMapping("/add")
    public String add(@RequestParam("name") String name,@RequestParam("phone") String phone) {
        Manager byPhone = managerService.findByPhone(phone);
        if (byPhone != null) {
            throw new BusinessException("该手机已注册");
        }
        int add = managerService.add(name, phone);
        if (add != 1) {
            throw new BusinessException("添加异常");
        }
        return "添加成功";
    }

    @PostMapping("/login")
    public Manager login(@RequestParam String phone) {

        Manager manager = managerService.findByPhone(phone);

        if (manager == null) {
            throw new BusinessException("账号不存在");
        }
        if (!manager.getStatus()) {
            throw new BusinessException("账号未启用");
        }
        return manager;
    }

    @PostMapping("/updateStatus")
    public String updateStatus(@RequestParam("phone") @Valid String phone, @RequestParam("status") Boolean status) {
        Manager manager = new Manager();
        manager.setPhone(phone);
        manager.setStatus(status);
        int update = managerService.update(manager);
        if (update != 1) {
            throw new BusinessException("修改异常");
        }
        return "修改成功";
    }

    @PostMapping("/delete")
    public String delete(@RequestParam("phone") @Valid String phone) {
        int delete = managerService.delete(phone);
        if (delete != 1) {
            throw new BusinessException("删除异常");
        }
        return "删除成功";
    }

    @PostMapping("/find")
    public Map<String ,Object> query(@RequestParam("field") String field, @RequestParam("page") Integer page) {
        Manager manager = new Manager();
        manager.setPhone(field);
        manager.setName(field);
        PageHelper.startPage(1, page);
        List<Manager> managers = managerService.find(manager);
        PageInfo<Manager> pageInfo = new PageInfo<>(managers);
        Map<String, Object> map = new HashMap<>(8);
        map.put("data", pageInfo.getList());
        map.put("total", pageInfo.getTotal());
        return map;
    }
}
